import time
import os
import  requests
# def long_time_task():
#     print('current process: %s'% os.getpid())
#     # time.sleep(2)
#     requests.get('https://www.baidu.com')
#     print('result: %s' % 8**50)
#
# if __name__ == '__main__':
#     print('parent process: %s' % os.getpid())
#     start = time.time()
#     for i in range(18):
#         long_time_task()
#     end = time.time()
#     print('用时： %s'%(end-start))  #  16.3434

from multiprocessing import Process
# if __name__ == '__main__':
#     print('parent process: %s' % os.getpid())
#     start = time.time()
#     ps = []
#     for i in range(8):
#         p = Process(target=long_time_task)
#         p.start()
#         ps.append(p)
#     for i in ps:
#         i.join()          # join() 是为了让母进程阻塞，等地啊子进程执行完成
#     end = time.time()
#     print('用时： %s'%(end-start))     #  2.238
#

''' Pool 进程池'''

def task(i):
    print('子进程: {} - 任务{}'.format(os.getpid(), i))
    requests.get('https://www.baidu.com')
    print("结果: {}".format(8 ** 50))

from multiprocessing import Pool, cpu_count
if __name__ == '__main__':
    start = time.time()
    p = Pool(4)
    for i in range(18):
        p.apply_async(task, args=(i,))

    p.close()
    p.join()  # 调用join之前必须先调用close或者terminate
    end = time.time()
    print('用时：%s'%(end-start))

''' 
    新创建的进程和进程的切换都是要好资源的，所以平时工作中进程数不能开太大
    同时可以运行的进程数一般受制于CPU的核数
    除了使用Process方法， 我们还可以使用Pool类创建多进程
'''